#ifndef PLCMODULE_H
#define PLCMODULE_H

#include <QObject>
#include <QGraphicsView>
#include <QPushButton>
#include "plc_graphics_scene.h"
#include "module_interface.h"
#include "plc_library_export.h"

// 前向声明
class ModbusManager;
class QWidget;
class QPointF;
class QSizeF;

class PLC_LIBRARY_API PlcModule : public IModule
{
    Q_OBJECT
public:
    explicit PlcModule(QWidget* ui, ModbusManager* modbusManager, QObject* parent = nullptr);
    void init() override;
    void setButtonStyle(QPushButton *button, const QString &text);

    void simpleSignals(PlcElement* elem);
    // 文件接口
    bool saveToFile(const QString& filePath) override;
    bool openFromFile(const QString& filePath) override;
    void resetDiagram();              // 新建/重置
    bool isModified() const override;
    void setModified(bool m) override;

    // 从外部（例如主窗口）触发比较元件状态刷新，更新比较元件的 ON/OFF
    void applyDRegisterSnapshot(const QHash<int, quint16>& dregs);
    void updateRegisterDisplay(int address, quint16 value);

    // 添加重新注册所有线圈的方法
    void againRegisterAllCoils();
    void againRegisterAllRegisters();
    void setSimulationRunning(bool running);

    // IModule接口实现
    void reset() override;
    QString getFileFilter() const override;
    QString getModuleName() const override;

    // 仿真相关方法实现
    void startSimulation(const QString& serialPort, int baudRate, int dataBits, int stopBits, int parity) override;
    void stopSimulation() override;
    bool isSimulationRunning() const override;
    
    // 设置Modbus管理器
    void setModbusManager(ModbusManager* modbusManager) override;

private Q_SLOTS:
    void prepareToCreateElement(PlcInstructionType type);
    void onElementCreated(PlcElement* item);
    // 实现IModule接口的Modbus数据更新方法
    void onCoilUpdated(int address, bool value) override;
    void onRegisterUpdated(int address, quint16 value) override;
    void onWriteCoilRequested(int address, bool value);
    // 添加复制粘贴槽函数
    void onCopyRequested();
    void onPasteRequested(const QPointF& scenePos);

private:
    // 私有方法，用于内部处理Modbus数据更新
    void updateCoilElements(int address, bool value);
    void updateRegisterElements(int address, quint16 value);
    QWidget* ui_;
    PlcGraphicsScene* scene_;

    // 修改标记
    bool isModified_ = false;

    ModbusManager* modbusManager_;
    QHash<int, quint16> dRegisterSnapshot_; // 存储D寄存器快照

    // 按钮
    QPushButton* normallyOpen_;
    QPushButton* normallyClosed_;
    QPushButton* coil_;
    QPushButton* greater_;
    QPushButton* greaterEqual_;
    QPushButton* less_;
    QPushButton* lessEqual_;
    QPushButton* equal_;
    QPushButton* notEqual_;

    PlcInstructionType copiedType_;
    QSizeF copiedSize_;
    bool copiedOn_;
    QString copiedPrefix_;
    int copiedValue1_;
    int copiedValue2_;
    bool hasCopiedItem_ = false;
};

#endif // PLCMODULE_H
